import os
import json
import commands
import ConfigParser
from time import time
from lib import constants as C
from lib.utils.read_settings import AnsibleSettings as AS
from lib.utils.display import Display

display = Display()
AS = AS()

class Playbook(object):
    def run(self, ip_list=[], refresh_cache=False):
        """ Get Ansible Data to Cache """

        self.refresh_cache = refresh_cache

        if type(ip_list) != list:
            display.error('run Error: ip_list is not list')
            return
   
        if not ip_list:
            self.batch_run(self.get_all_hosts())
        else:
            self.batch_run(ip_list)

        return

    def batch_run(self, ip_list):
        hosts_ips_part = []
        for ipx in range(0, len(ip_list), AS.hosts_batch_step):
            hosts_ips_part = ip_list[ipx:ipx + AS.hosts_batch_step]
            (status, output) = commands.getstatusoutput('ansible-playbook playbooks/run.yml -e \"{\'ip_list\': %s }\"' % json.dumps(ip_list))
            display.info('Host batch done -- %s' % str(json.dumps(hosts_ips_part)))

    def get_all_hosts(self):
        if AS.inventory:
            (status, output) = commands.getstatusoutput('ansible-inventory all --list -i' + AS.inventory)
        else:
            (status, output) = commands.getstatusoutput('ansible-inventory all --list')

        j_output = json.loads(output)
        dict_all_hosts = j_output['_meta']['hostvars']
        list_all_hosts=[]
        for key in dict_all_hosts:
            list_all_hosts.append(key)
        return list_all_hosts

    def is_cache_valid(self, cache_dir):
        """ Determines if the cache files have expired, or if it is still valid """

        if self.refresh_cache:
            return False
        else:
            try:
                if os.path.isdir(cache_dir):
                    mod_time = os.path.getmtime(cache_dir)
                    current_time = time()
                    if (mod_time + AS.cache_max_age) > current_time:
                        return True
            except Exception as e:
                display.error('is_cache_valid(self,cache_dir) error --- %s' % e)

                return False


def main():
    # print AS.sessions
    test=Playbook()
    test.run()
    test.run(ip_list='aaa')
    test.run(ip_list=['aaa'])

if __name__ == '__main__':
    main()
